/**
 * 中国9号健康产业有限公司
 * Copyright (C) JiuHaoHealth Corporation. All Rights Reserved
 */
package com.jiuhaohealth.log.launcher.conf;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.jiuhaohealth.log.launcher.handler.LogSocketClient;
/**
 * @author zhangguohua zhanggh@jiuhaohealth.com
 * 基本配置类
 */
public class LauncherConfig {
	//URL编码
	public static final String NAME_URL_ENCODING = "charset";
	private static final String DEFAULT_URL_ENCODING = "utf-8";
	
	//运行模式 如果该属性为DEBUG 将输出部分信息到Consol
	public static final String NAME_RUNMODE = "runmode";
	private static final String DEFAULT_RUNMODE = "RUN";
	
	//配置存储器
	private Map<String,String> storage;
	
	public LogSocketClient client;
	
	/**
	 * 根据属性名称获取配置
	 * @param key
	 * @return
	 */
	public String getAttr(String key){
		return storage.get(key);
	}
	/**
	 * 是否为调试模式
	 * @return
	 */
	public boolean isDebug(){
		if("DEBUG".equals(getAttr(LauncherConfig.NAME_RUNMODE).toUpperCase())){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 在调试模式下  输出调试信息 
	 * @param msg
	 */
	public void debugMsg(String msg){
		if(isDebug()){
			System.out.println(msg);
		}
	}
	
	public void errorMsg(String msg,Exception e){
		System.out.print(msg);
		e.printStackTrace();
	}
	
	public void infoMsg(String msg){
		System.out.print(msg);
	}
	
	/**
	 * 根据properties文件输入流初始化配置
	 * @param propertiesInputStream
	 * @return
	 */
	public boolean initConfig(InputStream propertiesInputStream){
		try {
			//先载入缺省值
			defaultConfig();
			
			//载入配置值  同名替换办法
			Properties prop = new Properties();
			prop.load(propertiesInputStream);
			
			Enumeration<?> keys = prop.propertyNames();
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				String value = prop.getProperty(key);
				
				storage.put(key, value);
			}
		} catch (IOException e) {
			errorMsg("由于以下异常造成加载配置失败！", e);
			return false;
		}
		debugMsg("当前模式为DEBUG模式 将打印调试信息到控制台！");
		debugMsg("配置文件载入成功.");
		return true;
	}
	
	/**
	 * 载入默认配置
	 */
	private void defaultConfig(){
		storage = new HashMap<String,String>();
		
		storage.put(LauncherConfig.NAME_URL_ENCODING, 
				LauncherConfig.DEFAULT_URL_ENCODING);
		storage.put(LauncherConfig.NAME_RUNMODE, 
				LauncherConfig.DEFAULT_RUNMODE);
	}
	
	private LauncherConfig(){}
	
	private static class LaunchConfigHolder{
		private static LauncherConfig instance = new LauncherConfig();
	}
	
	public static LauncherConfig getInstance(){
		return LaunchConfigHolder.instance;
	}
	
}
